import 'package:flutter/material.dart';
import 'app_exceptions.dart';

class ApiResponse<T> {
  int status = 0;
  int errorCode = 0;
  String errorDesc = "";
  int? statusCode = 0;
  dynamic response;
  Map<String, dynamic> result = {};
  AppException? _exception;
  T? t;

  ApiResponse.completed(this.response, this.statusCode) {
    if (response is Map<String, dynamic>) {
      status = response["status"] ?? 0;
      errorCode = response["error_code"] ?? 0;
      errorDesc = response["error_desc"] ?? "";
      result = response["result"] ?? {};
      if (isOk(ignoreT: true)) t = fromJson<T>(result, T);
    }
  }

  ApiResponse.ipCompleted(this.response, this.statusCode) {
    if (response is Map<String, dynamic>) {
      status = 1;
      errorCode = 0;
      errorDesc = "";
      result = response;
      if (isOk(ignoreT: true)) t = fromJson<T>(result, T);
    }
  }

  ApiResponse.cache(this.t) {
    this.status = t == null ? 0 : 1;
  }

  ApiResponse.error(this._exception) {
    errorCode = _exception?.code ?? 0;
    errorDesc = _exception?.message ?? "";
    debugPrint(toString());
  }

  ApiResponse.success(this.t) {
    this.status = 1;
  }

  ApiResponse.extra(this.errorCode, this.errorDesc) {
    debugPrint(toString());
  }

  bool isOk({bool ignoreT = false}) {
    return status == 1 && (ignoreT ? true : t != null);
  }

  AppException get exception => _exception ?? AppException(errorCode, errorDesc);

  @override
  String toString() {
    return "status:$status,errorCode:$errorCode,errorDesc:$errorDesc";
  }
}

T fromJson<T>(Map<String, dynamic> result, Type type) {
  debugPrint("fromJson()--type:$type");
  return result as T;
}
